package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 全局过滤器 通过token 判断用户登录
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       //获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //从请求中获取路径 并判断
        if ( request.getURI().getPath().contains("/login")) {
           //如果是登录请求直接放行
          return chain.filter(exchange);
        }
        //如果不是登录请求 就判断是否携带token 并判断token是否过期
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            //如果没有携带token说明非法登录 返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //并结束当前访问
            return response.setComplete();
        }

        try {
            //如果不为空则判断是否过期
            //传入token进行解析返回一个对象
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //从对象中获取时间结果
            int result = AppJwtUtil.verifyToken(claimsBody);
            //返回1和2 说明过期
            if (result==1||result==2) {
                // 返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //并结束当前访问
                return response.setComplete();
            }
        } catch (Exception e) {
            //如果中间报错 则报异常
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //如果都没问题则直接放行
        return chain.filter(exchange);
    }

    /**
     * 只有一个过滤器就默认配置，如果有多个，返回值越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
